package com.wpzf.ndhc.utils;

import com.alibaba.fastjson.JSONObject;
import com.wpzf.ndhc.domain.PartUploadDTO;
import com.wpzf.ndhc.domain.ResultRecordEntity;
import org.junit.Test;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class FileUtil
{
    GTYUtil gtyUtil=new GTYUtil();

    @Test
    public void multipartUpload() throws Exception
    {
        List<ResultRecordEntity> recordList=new ArrayList<>();
        ResultRecordEntity model=new ResultRecordEntity();
        model.setDatacode("WPZFNDTB2024_RECV");
        model.setXzqdm("150101");

        File file1=new File("D:\\1111\\130804.db");
        model.setSize(file1.length());
        model.setFilename("130804.db");
        model.setFjpath("D:\\1111\\130804.db");
        int MULTIPART_SIZE=50 * 1024; // 设置最大文件大小为10MB
        recordList.add(model);
        List<ResultRecordEntity> sectionList = recordList.stream().filter(e -> e.getSize() > MULTIPART_SIZE).collect(Collectors.toList());
        for (ResultRecordEntity section : sectionList) {
            HashMap<String, Object> params = new HashMap<>(4);
            params.put("code", section.getDatacode());
            params.put("regioncode", section.getXzqdm());
            params.put("filesize", section.getSize());
            params.put("filename", section.getFilename());
            // 请求
            Map<String, Object> rest=gtyUtil.getMultipartUploadPath(section.getXzqdm(),section.getSize(),section.getFilename());
            if(rest.get("code").equals(200))
            {
                JSONObject data = JSONObject.parseObject(rest.get("data").toString());
                JSONObject parturls = data.getJSONObject("parturls");
                // 赋值所有分段的url
                List<PartUploadDTO> partUploadList = new ArrayList<>();
                for (Map.Entry<String, Object> entry : parturls.entrySet()) {
                    String key = entry.getKey();
                    Object value = entry.getValue();
                    PartUploadDTO model1=new PartUploadDTO();
                    model1.setPartnumber(Integer.parseInt(key));
                    model1.setUrl(value.toString());
                    partUploadList.add(model1);
                }

                File file = new File(section.getFjpath());
                int segmentSize = Integer.parseInt(data.get("pktsize").toString());
                for (int i = 0; i < partUploadList.size(); i++) {
                    // 上传分段文件,并且获取响应头中的ETag数据
                    String etag = uploadSegment(partUploadList.get(i).getUrl(), file, segmentSize, i);
                    partUploadList.get(i).setEtag(etag.replaceAll("\"",""));
                }
                // 调用分段上传完成接口
                HashMap<String, Object> completeParam = new HashMap<>();
                completeParam.put("TaskID", data.get("taskid"));
                completeParam.put("ObjKey", data.get("objkey"));
                completeParam.put("PartTags", partUploadList);
                //接口没通
                Map<String, Object> rest1=gtyUtil.CompleteFlieUpload(data.get("taskid").toString(),data.get("objkey").toString(),partUploadList);
                if(rest1.get("code").equals(200)) {
                    section.setUrl(data.get("url").toString());
                }
            }
        }
    }

    public static String uploadSegment(String uploadUrl, File file, long segmentSize, int segmentIndex) throws MalformedURLException {
        URL presignedUrl= new URL(uploadUrl);
        BufferedOutputStream bufferedOutputStream = null;
        BufferedInputStream bufferedInputStream = null;
        try
        {
            HttpURLConnection httpURLConnection =
                    (HttpURLConnection) presignedUrl.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestProperty("Content-Type", "application/octet-stream");
            httpURLConnection.setRequestMethod("PUT");
            bufferedOutputStream = new
                    BufferedOutputStream(httpURLConnection.getOutputStream());
            bufferedInputStream = new
                    BufferedInputStream(new FileInputStream(file));

            long fileLength = file.length();
            long startPosition = segmentIndex * segmentSize;
            long endPosition = Math.min(startPosition + segmentSize, fileLength);
            int segmentLength = (int) (endPosition - startPosition); // 设置文件读取位置为当前分段的起始位置
            bufferedInputStream.skip(startPosition);
            byte[] buffer = new byte[segmentLength];
            int length =bufferedInputStream.read(buffer);

            if (length > 0) {
                bufferedOutputStream.write(buffer);
            }


            bufferedOutputStream.flush();
            bufferedOutputStream.close();
            if(httpURLConnection.getResponseCode()==200)
            {
                System.out.println(httpURLConnection.getResponseCode());
                System.out.println(httpURLConnection.getResponseMessage());
                { Map<String, List<String>> headerFields = httpURLConnection.getHeaderFields();
                    for (String key : headerFields.keySet())
                    { if ("ETag".equalsIgnoreCase(key))
                    { return headerFields.get(key).get(0);
                    }
                    }
                }
            }
            else
            {
                return null;
            }

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}